package com.clusterswisdom.horn.api.tmall.action.alipay.pushtrade;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.db.DbUtil;
import com.clusterswisdom.horn.api.ioc.HornResponse;
import com.clusterswisdom.horn.api.push.PushDataUtil;

public class PushOrderTrade {
	
	public static final String SQL_QUERYSPAN = "select * from billSpanstr where id = ?";
	
	public static final String SQL_COUNT = "select count(id) from OrderAccount where  billSpanStrId = ?";
	
	public static final String SQL_QUERYTRADE = "select * from OrderAccount where billSpanStrId = ? limit ?, ?";
	
	public static final String SQL_QUERYFEEE = "select * from fee where torderid = ? and billSpanstrid = ?";

	public static final int PAGE_SIZE = 100;
	
	public JSONObject pushData(HornResponse response)  throws Exception {
		Long tradeId = (Long)response.getData();
		//Long tradeId = 21l;
		long totalNum = getTotalNum(tradeId);
		if (totalNum == 0l) {
			return null;
		}
		
		JSONObject tradeSpanItem = getTradSpan(tradeId);
		if (tradeSpanItem == null) {
			return null;
		}
		
		int begin = 0;
		int count = 0;
		Connection conn = DbUtil.getUtil().getConnection();
		try {
			PreparedStatement counSql = conn.prepareStatement(SQL_COUNT);
			counSql.setLong(1, tradeId);
			ResultSet rs = counSql.executeQuery();
			
			while(rs.next()){
				count = rs.getInt(1);
				
			}
			
			do {
				PreparedStatement statement = conn.prepareStatement(SQL_QUERYTRADE);
				statement.setLong(1, tradeId);
				statement.setInt(2, begin);
				statement.setInt(3, PAGE_SIZE);
				
				List<JSONObject> pageDatas = new LinkedList<JSONObject>();
				ResultSet resultSet = statement.executeQuery();
				while (resultSet.next()) {
					JSONObject item = new JSONObject();
					item.put("torderid", resultSet.getString("torderid"));
					item.put("totalMoney", pushDataFormater.getDoubleNum(resultSet.getDouble("totalMoney")));
					//item.put("countMoney", Double.toString(resultSet.getDouble("countMoney")));
					double feeMoney = resultSet.getDouble("feeMoney");
					item.put("countMoney",pushDataFormater.getDoubleNum(resultSet.getDouble("countMoney")-feeMoney));
					
					item.put("feeMoney", pushDataFormater.getDoubleNum(feeMoney));  
					//item.put("differFee", Double.toString(resultSet.getDouble("differFee")));
					item.put("differFee", pushDataFormater.getDoubleNum(resultSet.getDouble("differFee")));
					item.put("busSalesAmount",pushDataFormater.getDoubleNum(resultSet.getDouble("countMoney")));
					item.put("feeList", getFeeList(conn, item.getString("torderid"),tradeId));
					pageDatas.add(item);
					
					begin++;
				}
				
				tradeSpanItem.put("orderList", pageDatas);
				
				String result=PushDataUtil.getUtil().pushData("${pushServer}/tmall/finance/sendTOrderAccounts.action", tradeSpanItem);
				
				//推送前存表操作，真实环境暂不存
				String sql = "insert into pushdata(name , value ,time) values(? ,? ,?)";
				PreparedStatement ps = conn.prepareStatement(sql);
				ps.setString(1, "pushTradeTrade"+result);
				ps.setString(2,tradeSpanItem.toString());
				ps.setDate(3, new Date(System.currentTimeMillis()));
				ps.executeUpdate();
				ps.close();
				conn.commit();
				
				
			} while (begin < count);
			
		} finally {
			DbUtil.getUtil().close();
			
		}
		return tradeSpanItem;
	}
	
	private List<JSONObject> getFeeList(Connection conn, String torderid ,long tradeId) throws SQLException {
		PreparedStatement statement = conn.prepareStatement(SQL_QUERYFEEE);
		statement.setString(1, torderid);
		statement.setLong(2, tradeId);
		
		List<JSONObject> feeDatas = new LinkedList<JSONObject>();
		ResultSet resultSet = statement.executeQuery();
		
		while (resultSet.next()) {
			JSONObject fee = new JSONObject();
			fee.put("feeCode", resultSet.getString("feeCode"));
			fee.put("feeName", resultSet.getString("feeName"));
			fee.put("feeValue", pushDataFormater.getDoubleNum(resultSet.getDouble("feeValue")));
			
			feeDatas.add(fee);
		}
		
		return feeDatas;
	}
	
	private long getTotalNum(Long id) throws SQLException {
		if (id == null) {
			return 0l;
		}
		
		Connection conn = DbUtil.getUtil().getConnection();
		PreparedStatement statement = conn.prepareStatement(SQL_COUNT);
		statement.setLong(1, id);
		
		ResultSet resultSet = statement.executeQuery();
		try {
			if (resultSet.next()) {
				return resultSet.getLong(1);
				
			} else {
				return 0l;
				
			}
			
		} finally {
			resultSet.close();
			
		}
	}
	
	private JSONObject getTradSpan(Long id) throws SQLException {
		Connection conn = DbUtil.getUtil().getConnection();
		PreparedStatement statement = conn.prepareStatement(SQL_QUERYSPAN);
		statement.setLong(1, id);
		ResultSet resultSet = statement.executeQuery();
		if (resultSet.next()) {
			JSONObject tradeSpan = new JSONObject();
			tradeSpan.put("channel", resultSet.getString("channel"));
			tradeSpan.put("billDateStr", resultSet.getString("billDateStr"));
			tradeSpan.put("billSpanStr", resultSet.getString("billSpanStr"));
			tradeSpan.put("billDate", resultSet.getString("billDate"));
			return tradeSpan;
			
		} else {
			return null;
			
		}
	}
}
